<template>
  <div class="box">
    <img src="../../../static/images/login.png" alt="">
    <div class="content">
      <!-- <span>获取头像昵称</span> -->
      <button class="btn" open-type="getUserInfo" lang="zh_CN" @getuserinfo="getUserInfo">获取头像昵称</button>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      iv: '',
      encryptedData: '',
      code: ''
    }
  },

  methods: {

    /**
     * 点击button获取用户信息
     */
    getUserInfo (e) {
      const that = this
      wx.setStorageSync('userInfo', e.target.userInfo)
      this.iv = e.target.iv
      this.encryptedData = e.target.encryptedData

      wx.login({
        success: function (res) {
          that.code = res.code

          // 创建session
          that.$http.post('/createSession', {
            body: {
              code: that.code
            }
          }).then(sessionRes => {
            const thirdSessionId = sessionRes.data.data.third_sessionId

            // 解析openid
            that.$http.post('/DecryptOpenid', {
              body: {
                iv: that.iv,
                encryptData: that.encryptedData,
                third_sessionId: thirdSessionId
              }
            }).then(openidRes => {
              const userInfo = JSON.parse(openidRes.data.data.userInfo)
              wx.setStorageSync('openid', userInfo.openId)

              wx.navigateBack({
                delta: 1
              })
            })
          })
        }
      })
    }
  }
}
</script>

<style scoped>
.box {
  width: 100vw;
  height: 100vh;
  vertical-align: middle;
  background: #821818;
  text-align: center;
}
img {
  height: 251rpx;
  width: 305rpx;
  margin-top: 240rpx;
}
.content {
  background: #fff;
  margin: -150rpx 130rpx 0 130rpx;
  padding-top: 220rpx;
  padding-bottom: 80rpx;
  border-radius: 20rpx;
}
.content span,
.content .btn {
  font-size: 30rpx;
  padding: 10rpx;
  margin: 0 60rpx;
  background: linear-gradient(to bottom, #ad242e, #c83240);
  border-radius: 100rpx;
  color: #fff;
}
</style>
